package com.db.stockexchange.app;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

import com.db.stockexchange.domain.Exchange;
import com.db.stockexchange.network.Server;

public class ExchangeServer {

	private static final String[] DEFAULT_SYMBOLS = {"MSFT", "GOOG", "ORCL"};
	
	private static List<String> readSymbolsListFromFile(String filename) throws FileNotFoundException {
		List<String> symbols = new ArrayList<>();
		Scanner scanner = new Scanner(new FileInputStream(filename));
		while (scanner.hasNext()) {
			symbols.add(scanner.nextLine());
		}
		scanner.close();
		return symbols;
	}
	
	public static void main(String[] args) {
		List<String> symbols;
		if (args.length > 0) {
			try {
				symbols = readSymbolsListFromFile(args[0]);
			} catch (FileNotFoundException e) {
				symbols = Arrays.asList(DEFAULT_SYMBOLS);
			}
		} else {
			symbols = Arrays.asList(DEFAULT_SYMBOLS);
		}
		
		Exchange exchange = new Exchange(symbols);
		Dispatcher dispatcher = new Dispatcher(exchange);
		Server server = new Server();
		server.addRequestListener(dispatcher);
		(new Thread(server)).start();
	}
}
